package com.hg.common.exception;

import com.google.common.base.Preconditions;
import com.hg.common.enums.ResultEnum;
import com.hg.common.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 全局异常处理器
 * Created by skh on 2017/12/22
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 处理全局异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResultVO handleException(Exception e) {
		log.error(e.getMessage(), e);
		return ResultVO.fail(ResultEnum.SYSTEM_ERROR.getCode(), ResultEnum.SYSTEM_ERROR.getMessage());
	}

	/**
	 * 处理自定义异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BizException.class)
	@ResponseBody
	public ResultVO handleBizException(BizException e) {
		log.error(e.getMessage(), e);
		return ResultVO.fail(e.getCode(), e.getMessage());
	}

	/**
	 * 处理参数异常
	 * @param e
	 * @return
	 */
	@ExceptionHandler(BindException.class)
	@ResponseBody
	public ResultVO handleBindException(BindException e) {
		List<FieldError> fieldErrors = e.getFieldErrors();
		Object target = e.getTarget();
		//拼接错误信息
		StringBuilder sb = new StringBuilder();
		for (FieldError fieldError : fieldErrors) {
			sb.append(fieldError.getDefaultMessage()).append(",");
		}
		String errorMsg = sb.substring(0, sb.length() - 1).toString();
		log.error("校验{}发生参数异常:{}", target,errorMsg);
		return ResultVO.fail(ResultEnum.PARAM_ERROR.getCode(), errorMsg);

	}

	/**
	 * 处理校验参数异常
	 *
	 * @param e
	 * @return
	 */
	@ExceptionHandler(ParamException.class)
	@ResponseBody
	public ResultVO handleParamException(ParamException e) {
		log.error("校验参数发生异常:{}",e.getMessage(), e);
		return ResultVO.fail(e.getCode(), e.getMessage());
	}
}